package main

import (
	"fmt"
	// "io/ioutil"
	"math"
	"os"
	"strconv"
	"time"
)

func main() {
	path := "E:\\qq\\916793573\\FileRecv\\sislog(5)\\sasis.log"
	t1 := time.Now()
	Split(path, 3)
	t2 := time.Now()
	fmt.Printf("耗时：%v s\n", t2.Sub(t1).Seconds())
}

//按文件个数分割
func Split(filePath string, num int) {
	fmt.Printf("文件路径：%s, 分割个数：%d\n", filePath, num)

	fileInfo, err := os.Stat(filePath)
	if err != nil {
		if os.IsNotExist(err) {
			fmt.Println("文件不存在！")
			return
		}
	}
	if fileInfo.IsDir() {
		fmt.Println("该路径是文件夹！")
		return
	}
	chunkSize := int64(math.Ceil(float64(fileInfo.Size()) / float64(num)))

	fmt.Printf("文件大小：%d , 分割后每个大小：%d\n", fileInfo.Size(), chunkSize)

	fi, err := os.OpenFile(filePath, os.O_RDONLY, os.ModePerm)
	if err != nil {
		fmt.Println(err)
		return
	}

	b := make([]byte, chunkSize)
	var i int64 = 1
	for ; i <= int64(num); i++ {
		var tempInt int64 = ((i - 1) * (chunkSize))
		fi.Seek(tempInt, 0)
		if len(b) > int(fileInfo.Size()-tempInt) {
			b = make([]byte, fileInfo.Size()-tempInt)
		}
		fi.Read(b)
		splitFile := filePath + "_part" + strconv.Itoa(int(i))
		f, err := os.OpenFile(splitFile, os.O_CREATE|os.O_WRONLY, os.ModePerm)
		fmt.Println("分割后：" + splitFile)
		if err != nil {
			fmt.Println(err)
			return
		}
		f.Write(b)
		f.Close()
	}
	fi.Close()
}
